Read N Characters Given Read4

The API: int read4(char *buf) reads 4 characters at a time from a file.

The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file.

By using the read4 API, implement the function int read(char *buf, int n) that reads n characters from the file.

Note:

The read function will only be called once for each test case.

Solution:

  1. /* The read4 API is defined in the parent class Reader4.
  2. int read4(char[] buf); */
  3. public class Solution extends Reader4 {
  4. /**
  5. * @param buf Destination buffer
  6. * @param n Maximum number of characters to read
  7. * @return The number of characters read
  8. */
  9. public int read(char[] buf, int n) {
  10. boolean eof = false; // end of file flag
  11. int total = 0; // total bytes have read
  12. char[] tmp = new char[4]; // temp buffer
  13. while (!eof && total < n) {
  14. int count = read4(tmp);
  15. // check if it's the end of the file
  16. eof = count < 4;
  17. // get the actual count
  18. count = Math.min(count, n - total);
  19. // copy from temp buffer to buf
  20. for (int i = 0; i < count; i++)
  21. buf[total++] = tmp[i];
  22. }
  23. return total;
  24. }
  25. }